<template>
  <header class="gym-header">
    <div class="logo-section">
      <div class="logo" @click="goToHome">
        <svg viewBox="0 0 24 24" class="h-6 w-6 text-gray-800">
          <path d="M12 2L2 7l10 5 10-5-10-5zm0 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z" fill="currentColor" />
        </svg>
        <span class="logo-text">FitPro</span>
      </div>
      <button class="admin-link" @click="goToAdminLogin">
        进入后台
      </button>
    </div>

    <!-- 右侧导航 -->
    <div class="nav-right">
      <!-- 调试信息 -->
      <div class="debug-info" style="color: white; font-size: 12px; margin-right: 10px;">
        登录状态: {{ userStore.getIsLoggedIn ? '已登录' : '未登录' }}
      </div>

      <!-- 用户下拉菜单（登录后显示） -->
      <div class="user-dropdown" v-if="userStore.getIsLoggedIn" @mouseenter="fetchUserInfoOnDropdown">
        <button class="user-button">
          <PixelAvatar size="32" />
          <i class="fa fa-chevron-down ml-2 text-xs"></i>
        </button>
        <div class="dropdown-menu">
          <!-- 用户昵称显示 - 修改为直接从store获取 -->
          <div class="dropdown-item user-info">
            <i class="fa fa-user-circle mr-2 text-blue-500"></i>
            <span class="user-nickname">
              {{ getUserNickname }}
            </span>
          </div>
          <hr class="dropdown-divider">
          <a
              href="/user/profile"
              target="_blank"
              class="dropdown-item"
          >
            <i class="fa fa-user-circle mr-2"></i>
            个人中心
          </a>
          <button
              class="dropdown-item logout-btn"
              @click="handleLogout"
          >
            <i class="fa fa-sign-out mr-2"></i>
            退出登录
          </button>
        </div>
      </div>

      <!-- 登录/注册按钮（未登录时显示） -->
      <div v-else class="auth-buttons">
        <button class="login-btn" @click="showLoginModal = true">
          <i class="fa fa-user"></i>
          登录
        </button>
      </div>
    </div>

    <LoginModal
        v-model:show="showLoginModal"
        @showRegister="showRegisterModal = true"
    />

    <RegisterModal
        v-model:show="showRegisterModal"
        @showLogin="showLoginModal = true"
    />
  </header>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/auth'
import axios from 'axios'
import LoginModal from '@/components/auth/LoginModal.vue'
import RegisterModal from '@/components/auth/RegisterModal.vue'
import PixelAvatar from './PixelAvatar.vue'

export default {
  name: 'AppHeader',
  components: {
    LoginModal,
    RegisterModal,
    PixelAvatar
  },
  setup() {
    const router = useRouter()
    const userStore = useUserStore()
    


    // 计算属性：获取用户昵称，确保正确显示
    const getUserNickname = computed(() => {
      if (userStore.userInfo) {
        // 尝试多种可能的昵称字段
        const nickname = userStore.userInfo.nickname ||
            userStore.userInfo.uNickname ||
            userStore.userInfo.name ||
            userStore.userInfo.username
        return nickname || '用户'
      }
      return '加载中...'
    })

    // 调试：检查登录状态
    console.log('AppHeader - 初始登录状态:', userStore.getIsLoggedIn)
    console.log('AppHeader - 用户信息:', userStore.userInfo)
    console.log('AppHeader - 用户Token:', userStore.token)
    console.log('AppHeader - 本地存储userToken:', typeof localStorage !== 'undefined' ? localStorage.getItem('userToken') : 'localStorage不可用')

    // 组件挂载时强制刷新登录状态
    onMounted(() => {
      console.log('AppHeader - 组件挂载，强制刷新登录状态')
      try {
        // 先手动从localStorage获取数据进行对比
        const storedToken = typeof localStorage !== 'undefined' ? localStorage.getItem('userToken') : null
        const storedUserInfo = typeof localStorage !== 'undefined' ? localStorage.getItem('userInfo') : null
        console.log('AppHeader - 本地存储数据:', { token: storedToken !== null, hasUserInfo: storedUserInfo !== null })

        userStore.refreshStatus()
        console.log('AppHeader - 刷新后登录状态:', {
          isLoggedIn: userStore.isLoggedIn,
          getIsLoggedIn: userStore.getIsLoggedIn,
          token: userStore.token
        })
      } catch (error) {
        console.error('AppHeader - 刷新状态失败:', error)
      }
    })

    // 优化：路由变化监听，确保在页面切换时保持登录状态
    // 使用router.beforeEach确保在路由变化前就同步状态
    router.beforeEach((to, from, next) => {
      console.log('AppHeader - 路由变化前同步状态:', from.path, '->', to.path)

      try {
        // 直接从localStorage同步到store，不依赖refreshStatus方法
        const storedToken = typeof localStorage !== 'undefined' ? localStorage.getItem('userToken') : null
        const storedUserInfo = typeof localStorage !== 'undefined' ? localStorage.getItem('userInfo') : null

        // 直接设置状态
        if (storedToken) {
          userStore.token = storedToken
          userStore.isLoggedIn = true

          if (storedUserInfo) {
            try {
              const userInfo = JSON.parse(storedUserInfo)
              userStore.userInfo = userInfo
            } catch (e) {
              console.error('解析用户信息失败:', e)
            }
          }
        }
      } catch (error) {
        console.error('AppHeader - 路由前同步失败:', error)
      }

      next() // 必须调用next()继续路由
    })

    // 路由完成后再次同步，确保页面完全加载后状态正确
    router.afterEach((to, from) => {
      console.log('AppHeader - 路由变化后同步状态:', from.path, '->', to.path)
      setTimeout(() => {
        try {
          userStore.refreshStatus()
        } catch (error) {
          console.error('AppHeader - 路由后同步失败:', error)
        }
      }, 0)
    })

    const showLoginModal = ref(false)
    const showRegisterModal = ref(false)
    const loginForm = ref({
      mobile: '',
      password: ''
    })
    const registerForm = ref({
      mobile: '',
      password: '',
      nickname: ''
    })
    const errorMessage = ref('')
    const registerErrorMessage = ref('')
    const rememberMe = ref(false)

    // 简化的返回首页方法，与全局同步机制配合
    const goToHome = () => {
      console.log('返回首页 - 执行路由跳转')

      // 由于App.vue中已经有全局的路由监听和状态同步，这里只需要简单跳转
      // 路由跳转前的状态同步由App.vue中的全局router.beforeEach处理
      router.push('/')

      // 额外触发一次全局同步以确保安全
      setTimeout(() => {
        try {
          const storedToken = localStorage.getItem('userToken')
          const storedUserInfo = localStorage.getItem('userInfo')

          if (storedToken) {
            userStore.token = storedToken
            userStore.isLoggedIn = true

            if (storedUserInfo) {
              userStore.userInfo = JSON.parse(storedUserInfo)
            }
          }
        } catch (e) {
          console.error('返回首页时状态同步失败:', e)
        }
      }, 0)
    }

    // 跳转到后台登录页面的方法
    const goToAdminLogin = () => {
      console.log('跳转到后台登录页面')
      router.push('/admin/login')
    }

    // 使用 window.open 在新标签页打开
    const goToAdminLoginNewTab = () => {
      const route = router.resolve({ name: 'AdminLogin' })
      window.open(route.href, '_blank')
    }

    // 处理登录
    const handleLogin = async () => {
      errorMessage.value = ''

      // 管理员登录（写死验证）
      if (loginForm.value.mobile === 'admin' && loginForm.value.password === 'admin') {
        localStorage.setItem('adminToken', 'admin-logged-in')
        showLoginModal.value = false
        loginForm.value.mobile = ''
        loginForm.value.password = ''
        router.replace('/admin/dashboard')
        return
      }

      // 模拟用户登录（临时解决方案）
      if (loginForm.value.mobile === 'user' && loginForm.value.password === 'user') {
        // 模拟用户登录成功 - 使用包含时间戳的token以避免冲突
        const timestamp = Date.now();
        const mockUser = {
          id: timestamp,
          mobile: 'user',
          nickname: '测试用户',
          token: 'user-mock-token-' + timestamp
        }
        localStorage.setItem('userToken', mockUser.token)
        localStorage.setItem('userInfo', JSON.stringify(mockUser))
        localStorage.setItem('userId', String(mockUser.id))
        userStore.setUserInfo(mockUser)

        showLoginModal.value = false
        loginForm.value.mobile = ''
        loginForm.value.password = ''
        router.replace('/user/dashboard')
        return
      }

      // 用户登录（调用后端API）
      try {
        const response = await axios.post('/api/users/login', {
          mobile: loginForm.value.mobile,
          password: loginForm.value.password
        })

        if (response.data && response.data.success) {
          // 保存用户token
          let userData = response.data.data
          localStorage.setItem('userToken', userData?.token || 'user-logged-in')

          // 登录成功后，调用getUserInfo API获取最新的用户信息
          try {
            const userId = userData.userId || userData.id || userData.uId
            if (userId) {
              console.log('登录成功，调用getUserInfo获取最新用户信息，用户ID:', userId)
              const userInfoResponse = await axios.get(`/api/users/${userId}`)

              if (userInfoResponse.data && userInfoResponse.data.success) {
                userData = userInfoResponse.data.data
                console.log('获取到的完整用户信息:', userData)
              }
            }
          } catch (userInfoError) {
            console.warn('获取用户详细信息失败，使用登录响应中的数据:', userInfoError)
          }

          // 更新本地存储和状态管理
          localStorage.setItem('userInfo', JSON.stringify(userData))
          userStore.setUserInfo(userData)
          console.log('用户信息已更新到store:', userStore.userInfo)

          showLoginModal.value = false
          loginForm.value.mobile = ''
          loginForm.value.password = ''
          router.replace('/user/dashboard')
        } else {
          errorMessage.value = response.data.message || '登录失败'
        }
      } catch (error) {
        console.error('登录失败:', error)

        // 提供更详细的错误信息
        if (error.code === 'ECONNREFUSED' || error.message?.includes('ECONNREFUSED')) {
          errorMessage.value = '后端服务暂不可用，请使用测试账号：手机号: user, 密码: user'
        } else if (error.response && error.response.data) {
          errorMessage.value = error.response.data.message || '登录失败，请检查手机号和密码'
        } else if (error.request) {
          errorMessage.value = '无法连接到服务器，请检查网络连接'
        } else {
          errorMessage.value = '登录过程中发生错误，请稍后重试'
        }
      }
    }

    // 下拉菜单展开时获取用户信息
    const fetchUserInfoOnDropdown = async () => {
      if (userStore.isLoggedIn && userStore.userId) {
        try {
          console.log('AppHeader - 下拉菜单展开，尝试获取最新用户信息，用户ID:', userStore.userId)
          const response = await axios.get(`/api/users/${userStore.userId}`)

          if (response.data && (response.data.code === 200 || response.data.success)) {
            const latestUserData = response.data.data
            console.log('AppHeader - 获取到最新用户信息:', latestUserData)
            // 更新localStorage和store
            localStorage.setItem('userInfo', JSON.stringify(latestUserData))
            userStore.setUserInfo(latestUserData)
          }
        } catch (error) {
          console.warn('AppHeader - 获取最新用户信息失败:', error)
        }
      }
    }

    // 处理注册
    const handleRegister = async () => {
      registerErrorMessage.value = ''

      // 模拟注册成功
      if (registerForm.value.mobile && registerForm.value.password && registerForm.value.nickname) {
        // 模拟注册成功
        const mockUser = {
          id: Date.now(),
          mobile: registerForm.value.mobile,
          nickname: registerForm.value.nickname,
          token: 'user-registered-token'
        }
        localStorage.setItem('userToken', mockUser.token)
        localStorage.setItem('userInfo', JSON.stringify(mockUser))
        userStore.setUserInfo(mockUser)

        showRegisterModal.value = false
        registerForm.value.mobile = ''
        registerForm.value.password = ''
        registerForm.value.nickname = ''
        router.replace('/user/dashboard')
        return
      } else {
        registerErrorMessage.value = '请填写所有必填字段'
      }

      // 实际注册逻辑（调用后端API）
      try {
        const response = await axios.post('/api/users/register', {
          mobile: registerForm.value.mobile,
          password: registerForm.value.password,
          nickname: registerForm.value.nickname
        })

        if (response.data && response.data.success) {
          // 注册成功后获取完整用户信息
          let userData = response.data.data || {}

          // 尝试获取完整用户信息
          try {
            const userId = userData.userId || userData.id || userData.uId
            if (userId) {
              console.log('AppHeader - 注册成功，调用getUserInfo获取最新用户信息，用户ID:', userId)
              const userInfoResponse = await axios.get(`/api/users/${userId}`)

              if (userInfoResponse.data && (userInfoResponse.data.code === 200 || userInfoResponse.data.success)) {
                userData = userInfoResponse.data.data
                console.log('AppHeader - 获取到的完整用户信息:', userData)
              }
            }
          } catch (userInfoError) {
            console.warn('AppHeader - 获取用户详细信息失败，使用注册响应中的数据:', userInfoError)
          }

          // 更新本地存储和状态管理
          localStorage.setItem('userToken', 'user-registered-token')
          localStorage.setItem('userInfo', JSON.stringify(userData))
          userStore.setUserInfo(userData)

          showRegisterModal.value = false
          registerForm.value.mobile = ''
          registerForm.value.password = ''
          registerForm.value.nickname = ''
          router.replace('/user/dashboard')
        } else {
          registerErrorMessage.value = response.data.message || '注册失败'
        }
      } catch (error) {
        console.error('注册失败:', error)
        if (error.response && error.response.data) {
          registerErrorMessage.value = error.response.data.message || '注册失败，请稍后重试'
        } else {
          registerErrorMessage.value = '网络错误，请稍后重试'
        }
      }
    }

    // 处理退出登录
    const handleLogout = () => {
      // 先显示确认对话框
      if (confirm('确定要退出登录吗？')) {
        userStore.logout()
        // 添加退出登录成功提示
        alert('您已退出登录')
        // 移除router.push('/')，因为logout方法内部已经包含了页面刷新
        // 保留足够的时间让用户看到提示消息
      }
      // 如果用户取消，则不执行任何操作
    }

    return {
      userStore,
      getUserNickname,
      showLoginModal,
      showRegisterModal,
      loginForm,
      registerForm,
      errorMessage,
      registerErrorMessage,
      rememberMe,
      goToHome,
      goToAdminLogin: goToAdminLoginNewTab,
      handleLogin,
      handleRegister,
      handleLogout,
      fetchUserInfoOnDropdown
    }
  }
}
</script>

<style scoped>
.gym-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 2rem;
  background-color: #1a202c; /* 改为黑色背景 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  position: relative;
  z-index: 100;
  height: 50px;
  flex-shrink: 0;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 2rem;
}

.logo {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 0.3rem 0.5rem;
  border-radius: 6px;
}

.logo:hover {
  background-color: rgba(255, 255, 255, 0.1);
  transform: scale(1.05);
}

.logo svg {
  color: #f6ad55;
}

.logo-text {
  font-size: 1.3rem; /* 增大字体 */
  font-weight: bold;
  color: #2d3748;
  background: linear-gradient(135deg, #f6ad55 0%, #ed8936 100%); /* 添加渐变背景 */
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  letter-spacing: -0.5px;
}

.admin-link {
  background: none;
  border: none;
  color: white;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 0.3rem 0.8rem;
  border-radius: 4px;
  text-decoration: none;
}

.admin-link:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #f6ad55;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 1.5rem;
}

.auth-buttons {
  display: flex;
  gap: 1rem;
}

.user-dropdown {
  position: relative;
}

.user-button {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 0.4rem 0.6rem;
  border-radius: 6px;
  transition: background-color 0.2s ease;
  font-size: 0.9rem;
}

/* 为像素头像设置CSS变量 */
.user-button :deep(.pixel-grid) {
  --grid-size: 8;
  --pixel-size: 4px;
}

.user-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 美化下拉菜单样式 */
.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
  padding: 0.5rem 0;
  min-width: 180px;
  opacity: 0;
  visibility: hidden;
  transform: translateY(-10px);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  z-index: 1000;
}

.user-dropdown:hover .dropdown-menu {
  opacity: 1;
  visibility: visible;
  transform: translateY(5px);
}

.dropdown-item {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0.8rem 1.2rem;
  background: none;
  border: none;
  text-align: left;
  color: #e2e8f0;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.9rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

/* 用户信息显示样式 - 美化 */
.dropdown-item.user-info {
  cursor: default;
  font-weight: 600;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.05) 100%);
  color: #f8fafc;
  border-radius: 8px 8px 0 0;
  margin: 0.2rem;
  padding: 1rem 1.2rem;
  border-bottom: 1px solid rgba(102, 126, 234, 0.2);
}

.user-nickname {
  font-weight: 600;
  color: #fbbf24;
  font-size: 0.95rem;
}

.dropdown-item.user-info:hover {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.08) 100%);
  color: #f8fafc;
}

/* 分隔线样式 */
.dropdown-divider {
  margin: 0.3rem 0;
  border: 0;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.dropdown-item:not(.user-info):hover {
  background: rgba(255, 255, 255, 0.1);
  color: #fbbf24;
  transform: translateX(5px);
}

.dropdown-item i {
  width: 16px;
  text-align: center;
  margin-right: 0.8rem;
  font-size: 0.85rem;
  color: #94a3b8;
  transition: color 0.2s ease;
}

.dropdown-item:hover i {
  color: #fbbf24;
}

.logout-btn {
  color: #fecaca;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 0 0 8px 8px;
  margin-top: 0.2rem;
}

.logout-btn:hover {
  background: rgba(254, 202, 202, 0.1);
  color: #fca5a5;
}

/* 登录按钮样式 */
.login-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
  box-shadow: 0 2px 6px rgba(45, 55, 72, 0.3);
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(45, 55, 72, 0.4);
  background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
}

.login-btn i {
  font-size: 0.8rem;
}

.login-modal .modal-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.register-modal .modal-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.modal-header h3 {
  margin: 0;
  color: #2d3748;
  font-size: 1.8rem;
  font-weight: 700;
}

.input-with-icon i {
  position: absolute;
  left: 1rem;
  color: #a0aec0;
  z-index: 1;
  font-size: 1rem;
}

.input-with-icon input {
  width: 100%;
  padding: 1rem 1rem 1rem 3rem;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background-color: #f8fafc;
}

.input-with-icon input:focus {
  outline: none;
  border-color: #4299e1;
  background-color: white;
  box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
}

.remember-me input:checked + .checkmark {
  background: #4299e1;
  border-color: #4299e1;
}

.remember-me input:checked + .checkmark::after {
  content: '✓';
  position: absolute;
  color: white;
  font-size: 0.8rem;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.fitness-motto p {
  margin: 0;
  color: #718096;
  font-size: 0.9rem;
  font-weight: 500;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .gym-header {
    padding: 0.5rem 1rem;
    height: 45px;
  }

  .logo-section {
    gap: 1rem;
  }

  .nav-right {
    gap: 1rem;
  }

  .nav-link {
    font-size: 0.85rem;
  }

  .login-btn {
    padding: 0.4rem 0.8rem;
    font-size: 0.8rem;
  }

  .user-button {
    font-size: 0.85rem;
    padding: 0.3rem 0.5rem;
  }

  .modal-content {
    padding: 2rem;
    margin: 1rem;
  }

  .dropdown-menu {
    min-width: 160px;
    right: -10px;
  }
}
</style>